//
//  BRRentingViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/10/29.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRRentingViewController.h"
#import "BRRentStateVC.h"

#import "Lottie-Swift.h"

@interface BRRentingViewController ()
{
//    QMUILabel *_timeL;
    
}

@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, strong) dispatch_source_t timerOreder;

@property (nonatomic,assign) BOOL isRunning;

//@property (nonatomic,strong) UIImageView *proccessImg;

@property (nonatomic,strong) CompatibleAnimationView *lottieView;

@end

@implementation BRRentingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    
    [self setUI];
    
    self.isRunning = YES;
    
    
    [self startTime];
    [self startTimeInOrder];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
//    [self br_imgRun];
    
    [self.lottieView play];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self cancelAllTimer];
    [self.lottieView stop];
}

#pragma mark - Requset --
- (void)requestCheckOrder {
    
    WS(weakSelf);
    [[BRRequestManager shared] GET:[BRAPI rentResult:self.orderNo] params:@{} succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {

        NSDictionary *dic = dataDict[@"data"];
        if ([dic isKindOfClass:[NSDictionary class]]) {

            NSString *orderNo = dic[@"orderNo"];
            if (!BR_StringIsEmpty(orderNo)) {
                [weakSelf cancelAllTimer];
                // succ
                [weakSelf rentState:YES];
            }

        }

    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [weakSelf cancelAllTimer];
        //
        [weakSelf rentState:NO];
    }];
}


#pragma mark - Action --
//定时器
-(void)startTime{
//    __weak __typeof__(self) weakSelf = self;
//    __block int progressNum1 = 0; //倒计时时间
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
//    self.timer = _timer;
//    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 0.05 * NSEC_PER_SEC, 0); //每秒执行
//    
//    dispatch_source_set_event_handler(_timer, ^{
//        if(progressNum1 > 99){ //倒计时结束，关闭
//            
//            [weakSelf cancelTimer:_timer doMain:^{
//                
//            }];
//        }else{
//
//            NSString *strTime = [NSString stringWithFormat:@"%d %%", progressNum1];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                //设置界面的按钮显示 根据自己需求设置
//                NSLog(@"____%@",strTime);
//                self->_timeL.text = strTime;
//            });
//            progressNum1 ++;
//        }
//    });
//    
//    dispatch_resume(_timer);
    
}

//定时器
-(void)startTimeInOrder {
    __weak __typeof__(self) weakSelf = self;
    __block int progressNum = 0; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    self.timerOreder = _timer;
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 3 * NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        if(progressNum >= 20){ //倒计时结束，关闭
            NSLog(@"订单结束");
            [weakSelf cancelTimer:_timer doMain:^{
                
                
                [weakSelf rentState:NO];
            }];
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf requestCheckOrder];
                NSLog(@"请求次数--- %d --",progressNum);
            });
            progressNum++;
        }
    });
    
    dispatch_resume(_timer);
    
}


// 结束定时器并在异步主线程处理业务
- (void)cancelTimer:(dispatch_source_t)timer doMain:(void(^)(void))doMain {
    if (!timer) {
        doMain();
        return;
    }
    dispatch_source_cancel(timer);
    
    dispatch_async(dispatch_get_main_queue(), doMain);
}

- (void)cancelAllTimer {
    
    if (self.timerOreder) {
        [self cancelTimer:self.timerOreder doMain:^{
                
        }];
    }
    if (self.timer) {
        [self cancelTimer:self.timer doMain:^{
                
        }];
    }
    
//    [self br_imgStop];
    
}

- (void)br_imgRun {
    dispatch_async(dispatch_get_main_queue(), ^{
        CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 4.0]; // 旋转两圈
        rotationAnimation.duration = 0.5; // 动画持续时间（一圈的时间）
        rotationAnimation.repeatCount = HUGE_VALF; // 重复次数（设置为无限大）

//        [self.proccessImg.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    });
    
}

- (void)br_imgStop {
//    [self.proccessImg.layer removeAnimationForKey:@"rotationAnimation"];
}

- (void)rentState:(BOOL)isSucc {
    
    if (isSucc) {
        
        [self.navigationController popToRootViewControllerAnimated:YES];
        
        return;
    }
    BRRentStateVC *vc = [[BRRentStateVC alloc] init];
    vc.rentSucc = isSucc;
    vc.orderNo = self.orderNo;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - SET UI --
- (void)setUI {
    
    [self br_createTop:@"" imageStr:@""];
    
    UIView *contV = [[UIView alloc] init];
    [self.view addSubview:contV];
    [contV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.centerX.offset(0);
        make.top.offset(28 + kSafeAreaTopHeight);
        make.bottom.offset(0);
    }];
    
//    self.proccessImg = [[UIImageView alloc] init];
//    self.proccessImg.image = UIImageMake(@"rent_ring");
    [contV addSubview:self.lottieView];
    [self.lottieView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.centerX.offset(0);
        make.width.height.mas_equalTo(160);
    }];
    
    
//    _timeL = [BRToolsView br_label:@"0%" textColor:UIColorMakeWithHex(@"#889DBB") font:[UIFont fontR:20]];
//    [contV addSubview:_timeL];
//    [_timeL mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.offset(0);
//        make.centerX.offset(0);
//    }];
    
    QMUILabel *proL = [BRToolsView br_label:Localized(@"rent_ejecting") textColor:UIColorMakeWithHex(@"#889DBB") font:[UIFont fontB:20]];
    proL.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:proL];
    [proL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.lottieView.mas_bottom).offset(0);
        make.centerX.offset(0);
    }];
    QMUILabel *proTextL = [BRToolsView br_label:Localized(@"rent_donotClose") textColor:UIColorMakeWithHex(@"#889DBB") font:[UIFont fontM:14]];
    proTextL.textAlignment = NSTextAlignmentCenter;
    proTextL.numberOfLines = 0;
    [self.view addSubview:proTextL];
    [proTextL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(proL.mas_bottom).offset(8);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
//    CGRect defaultFrame = CGRectMake(kScreenWidth / 2.0 - 44, kScreenHeight - kSafeAreaBottomHeight - 132, 88, 88);
//    QMUILabel *time = [[QMUILabel alloc] initWithFrame:defaultFrame];
//    time.layer.borderColor = UIColor.qd_tintColor3.CGColor;
//    time.layer.borderWidth = 1;
//    time.layer.cornerRadius = defaultFrame.size.height / 2.0;
//    time.textAlignment = NSTextAlignmentCenter;
//    time.textColor = UIColor.qd_tintColor3;
//    time.text = @"0";
//    [self.view addSubview:time];
//    _timeL = time;
    
}

- (CompatibleAnimationView *)lottieView {
    
    if (_lottieView == nil) {
        NSString *patch = [BRThemeManage br_patchStr:@"Loading" type:@"json"];
        _lottieView = [[CompatibleAnimationView alloc] initWithUrl:[NSURL fileURLWithPath:patch]];
        _lottieView.frame = CGRectMake(0, 0, 85, 85);
        _lottieView.loopAnimationCount = -1;
    }
    return _lottieView;
}



- (BOOL)forceEnableInteractivePopGestureRecognizer {
    // 屏蔽右滑返回
    return !self.isRunning;

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


@interface BRRentStatusView ()
{
    UIImageView *_statusImg;
    QMUILabel *_statusL;
    QMUILabel *_statusSubL;
}
@end

@implementation BRRentStatusView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)setIsSucc:(BOOL)isSucc {
    _isSucc = isSucc;
    
    UIImage *imgS = [UIImage qd_successImage];
    NSString *textS = [NSString stringWithFormat:@"%@",Localized(@"Rent_result_success")];
    NSString *subTextS = Localized(@"Rent_success_alert");
    
    if (!isSucc) {
        imgS = UIImageMake(@"rent_fault");
        textS = [NSString stringWithFormat:@"%@",Localized(@"Rent_result_failed")];
        subTextS = Localized(@"Rent_failed_alert");
    }
    _statusImg.image = imgS;
    _statusL.text = textS;
    _statusSubL.text = subTextS;
}

- (void)setUI {
    
    UIImageView *defaultImg = [[UIImageView alloc] init];
    defaultImg.image = [UIImage qd_successImage];
    [self addSubview:defaultImg];
    [defaultImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(0);
        make.width.height.mas_equalTo(141);
        make.centerX.equalTo(self);
    }];
    NSString *titleStr = @"--";
    QMUILabel *depositL = [[QMUILabel alloc] init];
    depositL.text = titleStr;
    depositL.textColor = UIColor.qd_titleTextColor;
    depositL.font = [UIFont br_fontB:21];
    depositL.textAlignment = NSTextAlignmentCenter;
    depositL.numberOfLines = 0;
    [self addSubview:depositL];
    [depositL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
//        make.centerX.equalTo(self);
        make.top.equalTo(defaultImg.mas_bottom).offset(4);
       
    }];
    
    QMUILabel *subL = [[QMUILabel alloc] init];
    subL.text = titleStr;
    subL.textColor = UIColor.qd_descriptionTextColor;
    subL.font = [UIFont br_fontM:14];
    subL.textAlignment = NSTextAlignmentCenter;
    subL.numberOfLines = 0;
    [self addSubview:subL];
    [subL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self);
//        make.centerX.equalTo(self);
        make.top.equalTo(depositL.mas_bottom).offset(4);
        make.bottom.equalTo(self);
    }];
    
    _statusImg = defaultImg;
    _statusL = depositL;
    _statusSubL = subL;
}

@end
